// var mqtt = require('mqtt')
import mqtt from 'mqtt'
import eventbus from "@/until/eventbus";
export default function mqttMSG(data) {
  var client
  let arr = data.config
  let mqttconfig = data.mqtt
  let time = Date.now().toString()
  let nowtime = time.substring(time.length - 4)
  const options = {
    connectTimeout: 30 * 1000,
    clientId: '9ZYD_' + nowtime + Math.random().toString(36).substring(2, 8),
    username: mqttconfig[2],
    password: mqttconfig[3],
    clean: true,
    addr: mqttconfig[0],
    mqttport: '8083'
  }
  let optionM = {
    KeepAlive: 100,
    CleanSession: true,
    SSL: false,
    reconnect: true
  }
  // console.log(options.clientId);
  client = mqtt.connect('ws://'+options.addr+':'+options.mqttport+'/mqtt', options)
  if (client.connected) {
    client.end()
  }

  // 连接
  client.on('connect', e => {
    // console.log(e);
    console.log('账户ID:' + options.clientId + '连接成功:');
    client.subscribe(arr, error => {
      if (!error) {
        // console.log(arr);
        console.log('账户ID:' + options.clientId + '订阅成功');
      } else {
        console.log('订阅失败');
        // console.log(error);
      }
    })
  })
  let topicarr = []
  // 消息处理
  let arrf = {} 
  client.on('message', (topic, message) => {
    const jsonString = Buffer.from(message).toString('utf-8')
    const parseData = JSON.parse(jsonString)
    if(parseData.channel_size == 6){
      // console.log("GNSS");
      // console.log(parseData.timestamp);
      // console.log(parseData);
      eventbus.emit('GNSS',parseData)
      console.log(parseData.packet_index);
    }else{
      eventbus.emit('9ZYD',parseData)
      // console.log("陀螺仪");
      // console.log(parseData.timestamp);
      // console.log(parseData);
    }
  })
  // 断开发起重连
  client.on("reconnect", error => {
    console.log("正在重连:");
  });
  // 链接异常处理
  client.on("error", error => {
    console.log("连接失败:");
  });
  

  
}